package com.tuanzi.loan.web.bean.galaxycard;

import com.tuanzi.loan.business.entity.CurrentUser;
import com.tuanzi.loan.business.entity.galaxycard.*;
import com.tuanzi.loan.business.service.galaxycard.GalaxyCardUserPrivilegeService;
import com.tuanzi.loan.business.service.galaxycard.impl.GalaxyCardUserPrivilegeServiceImpl;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.web.configuration.JSFListingBean;

import com.tuanzi.loan.vo.request.galaxycard.GalaxyCardUserPrivilegeSearchRequest;
import com.tuanzi.loan.vo.response.galaxycard.GalaxyCardUserPrivilegeSearchResponse;
import com.tuanzi.loan.web.lazy.galaxycard.GalaxyCardUserPrivilegeDataModel;

import lombok.Data;
import lombok.EqualsAndHashCode;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.faces.bean.ViewScoped;
import java.io.IOException;
import java.util.*;

/**
 * 银河黑卡用户权益
 * @author JinRuiyang 2018/1/9 14:31:17
 */
@Debug
@Data
@Component
@ViewScoped
@EqualsAndHashCode(callSuper = true)
public class GalaxyCardUserPrivilegeBean extends JSFListingBean<GalaxyCardUserPrivilegeSearchRequest, GalaxyCardUserPrivilegeSearchResponse> {

    private List<GalaxyCardPrivilegeStatus> privilegeStatuses;
    private List<GalaxyCardPrivilege> privileges;

    private List<GalaxyCardPrivilegeStatus> choosePrivilegeStatuses;
    private GalaxyCardUserPrivilege chooseUserPrivilege;
    private GalaxyCardUserPrivilegeSearchResponse chooseUserPrivilegeResponse;
    private GalaxyCardPrivilegeExpress express;
    private GalaxyCardPrivilegeCDKey cdKey;

    private Long importedCDKeyPrivilegeId;
    private String importedCDKeyFileInfo;
    private Map<String,GalaxyCardPrivilegeCDKey> beingImportedCDKeys;

    @Autowired
    private GalaxyCardUserPrivilegeService galaxyCardUserPrivilegeService;

    @PostConstruct
    private void init() {
        initLazyDataModel();
    }

    public void onReset() {
        initLazyDataModel();
        privilegeStatuses = Collections.emptyList();
    }

    public void onRefresh(){
        lazyDataModel = new GalaxyCardUserPrivilegeDataModel($);
        addSuccessfullyMessage();
    }

    private void cleanChooseScope(){
        choosePrivilegeStatuses = null;
        chooseUserPrivilege = null;
        chooseUserPrivilegeResponse = null;
        express = null;
        cdKey = null;
    }

    public void handleCDKeyImport(FileUploadEvent event) {
        UploadedFile file = event.getFile();
        if (beingImportedCDKeys == null)
            beingImportedCDKeys = new HashMap<>();
        try {
            XSSFWorkbook wb = new XSSFWorkbook(file.getInputstream());
            XSSFSheet sheet = wb.getSheetAt(0);
            Date currentDate = new Date();
            String operatorName = CurrentUser.get().getName();
            Integer startIndex = beingImportedCDKeys.size();
            for (int i = 0; i <= sheet.getLastRowNum(); i++) {
                XSSFRow row = sheet.getRow(i);
                if (row == null)
                    continue;
                XSSFCell cell = row.getCell(0);
                if (cell == null)
                    continue;
                String cdKey = cell.getStringCellValue();
                if (StringUtils.isNotBlank(cdKey)){
                    if (beingImportedCDKeys.get(cdKey) != null){
                        addErrorMessage("激活码列表中读取到重复的内容，请检查后重试");
                        beingImportedCDKeys = null;
                        importedCDKeyFileInfo = null;
                        return;
                    }
                    GalaxyCardPrivilegeCDKey privilegeCDKey = new GalaxyCardPrivilegeCDKey();
                    privilegeCDKey.setActive_code(cdKey);
                    privilegeCDKey.setCreate_time(currentDate);
                    privilegeCDKey.setUpdate_time(currentDate);
                    privilegeCDKey.setOperator_name(operatorName);
                    privilegeCDKey.setPrivilegeId(importedCDKeyPrivilegeId);
                    privilegeCDKey.setStatus(1);
                    beingImportedCDKeys.put(cdKey, privilegeCDKey);
                }
            }
            if (importedCDKeyFileInfo == null)
                importedCDKeyFileInfo = "";
            else importedCDKeyFileInfo +="; ";
            importedCDKeyFileInfo += "[读取："+(beingImportedCDKeys.size() - startIndex)+"个]"+file.getFileName();
            addInfoMessage(String.format("从文件: %s 中成功读取了 %d 个激活码", file.getFileName(), beingImportedCDKeys.size() - startIndex));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void onCancelImportCDKeys() {
        importedCDKeyPrivilegeId = null;
        beingImportedCDKeys = null;
        importedCDKeyFileInfo = null;
    }

    public void onConfirmImportCDKeys() {
        if (importedCDKeyPrivilegeId == null){
            addErrorMessage("确认导入前请先选择权益");
            return;
        }
        Integer insertCDKeyCount = 0;
        Integer duplieCDKeyCount = 0;
        Set<String> dbCDKeys = galaxyCardUserPrivilegeService.getPrivilegeCDKeyByPrivilegeId(importedCDKeyPrivilegeId);
        for (GalaxyCardPrivilegeCDKey cdKey : beingImportedCDKeys.values()){
            if (dbCDKeys.contains(cdKey.getActive_code())){
                duplieCDKeyCount ++;
                continue;
            }
            cdKey.setPrivilegeId(importedCDKeyPrivilegeId);
            galaxyCardUserPrivilegeService.insert(cdKey);
            dbCDKeys.add(cdKey.getActive_code());
            insertCDKeyCount++;
        }
        addInfoMessage("激活码导入成功 " +  String.format("文件读入：%d个, 成功导入：%d个, 数据库重复忽略：%d个",
                beingImportedCDKeys.size(), insertCDKeyCount, duplieCDKeyCount));
        onCancelImportCDKeys();
    }


    public void onChoosePrivilegeStatus(GalaxyCardUserPrivilegeSearchResponse response){
        if (Objects.isNull(response) || Objects.isNull(response.getPk()))
            throw new NullPointerException("找不到改用户权益关联信息");
        cleanChooseScope();
        chooseUserPrivilegeResponse = response;
        chooseUserPrivilege = galaxyCardUserPrivilegeService.findById(response.getPk());
        if (Objects.nonNull(chooseUserPrivilege)){
            choosePrivilegeStatuses = galaxyCardUserPrivilegeService.getStatusByPrivilegeId(chooseUserPrivilege.getPrivilegeId());
            // 统一的快递信息
            if (Objects.nonNull(chooseUserPrivilege.getExpressId()))
                express = galaxyCardUserPrivilegeService.findExpressById(chooseUserPrivilege.getExpressId());
            if (Objects.nonNull(chooseUserPrivilege.getBusinessId())){
                switch (chooseUserPrivilege.getCode()){
                    case "activation-code":
                        cdKey = galaxyCardUserPrivilegeService.findCDKeyById(chooseUserPrivilege.getBusinessId());
                        break;
                }
            }
        }
        else{
            choosePrivilegeStatuses = null;
            addErrorMessage("找不到改用户权益关联信息");
        }
    }

    public void onSendExpress(){
        if (StringUtils.isBlank(Objects.requireNonNull(express).getExpress_no()))
            addErrorMessage("请先填写快递单号再进行提交");
        express.setUpdateTime(new Date());
        express.setOperator_name(Objects.requireNonNull(CurrentUser.get()).getName());
        galaxyCardUserPrivilegeService.update(express, chooseUserPrivilege);
    }

    public void onChangePrivilegeStatus(){
        if (chooseUserPrivilege != null){
            galaxyCardUserPrivilegeService.update(chooseUserPrivilege);
            addSuccessfullyMessage();
        }
        else
            addErrorMessage("找不到改用户权益关联信息");
    }

    public void onChoosePrivilege(){
        if ($.getPrivilege() != null){
            privilegeStatuses = galaxyCardUserPrivilegeService.getStatusByPrivilegeId($.getPrivilege());
        }
        if ($.getPrivilege() == null){
            $.setPrivilege(null);
        }
    }

    public void onFlushCache(){
        GalaxyCardUserPrivilegeServiceImpl.cleanCache();
        addSuccessfullyMessage();
    }

    private void initLazyDataModel() {
        privileges = galaxyCardUserPrivilegeService.getPrivileges();
        $ = new GalaxyCardUserPrivilegeSearchRequest();
        lazyDataModel = new GalaxyCardUserPrivilegeDataModel($);
    }
}